const path = require('path');
const fs = require('fs');

module.exports = class extends think.Controller {
  async __before() {
    const is_login = await this.islogin();
    if (!is_login) {
      return this.fail('非法操作!');
    }
  }

  async islogin() {
    const user = await this.session('userInfo');
    const res = think.isEmpty(user) ? false : user.uid;
    return res;
  }

  async indexAction() {
    console.log(this.config('systemInfo.storage_type'))
    this.assign({
      $mode: this.get().method,
      $uptype: this.config('systemInfo.storage_type'),
      $type: this.get().type,
      $field: this.get().field,
      $mimes: this.get().type,
      uploadURI: '/ext/webupload/index/upstate'
    })
    return this.display();
  }

  async uploadAction() {
    // const file = think.extend({}, this.file('file'));
    // const filePath = file.path;
    // const extname = path.extname(file.name);
    // const basename = path.basename(filepath) + extname;
    let data;
    if (Number(this.config('ext.qiniu.is')) === 1) {
      const qiniu = this.service('ext/qiniu');
      const uppic = await qiniu.uploadpic(filepath, basename);
      if (!think.isEmpty(uppic)) {
        data = {
          create_time: new Date().getTime(),
          name: file.name,
          savename: basename,
          mime: file.type,
          size: file.size,
          location: 1,
          sha1: uppic.hash,
          md5: think.md5(basename)
        };
      }
    } else {
      // const uploadPath = think.resource + '/upload/download/' + dateformat('Y-m-d', new Date().getTime());
      // think.mkdir(uploadPath);
      // fs.renameSync(filepath, uploadPath + '/' + basename);
      await this.controller('ext/webupload').upload('/upload/download/', '', '', () => {
        think.logger.debug('上传成功')
      })
      file.path = uploadPath + '/' + basename;
      if (think.isFile(file.path)) {
        data = {
          savepath: '/upload/download/' + dateformat('Y-m-d', new Date().getTime()) + '/',
          create_time: new Date().getTime(),
          name: file.name,
          savename: basename,
          mime: file.type,
          size: file.size,
          md5: think.md5(basename)
        };
        // console.log(data);
        var res = await this.model('file').add(data);
        return this.json({id: res, size: file.size});
      }
    }
  }
}